package com.ajouroid.smartcoworker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddFriendsActivity extends Activity {
	static final int PROGRESS_DIALOG = 0;
	Button btn_search;
	Button btn_invite;
	Button btn_delFriends;
	ImageButton btn_close;
	ListView friend_list;
	ListView result_list;
	ArrayList<User> exist_list; //이미 팀원 추가된 목록
	ArrayList<User> arr_user_r;
	ArrayList<User> arr_user_f;
	ArrayList<User> arr_from_rlist; //검색결과에서 팀원추가시
	ArrayList<User> arr_from_flist; //친구리스트에서 팀원추가시
	CheckBox []list_chk;
	ArrAdapter r_adapter;
	ArrAdapter f_adapter;
	EditText input;
	Spinner mSpinner = null;
    ArrayAdapter<String> mSpinnerAdapter = null;
    Intent before_intent;
    Intent intent;
	String err_msg = null;
	String myId = null;
	int[] arr_user_f_flag;
	public boolean owner = false;
	ProgressDialog uploadDialog;
	HashMap<String, Bitmap> f_img_factory;
	
	
	@SuppressLint("UseSparseArrays")
	@SuppressWarnings({ "unchecked" })
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
		setContentView(R.layout.activity_addfriends);		
		friend_list = (ListView) findViewById(R.id.addfriends_f_list);
		result_list = (ListView) findViewById(R.id.addfriends_r_list);
		
		btn_invite = (Button) findViewById(R.id.addfriends_btn_invite);
		btn_close = (ImageButton) findViewById(R.id.addfriends_btn_close);
		
		btn_delFriends = (Button) findViewById(R.id.addfriends_btn_delfriends);
		btn_search = (Button) findViewById(R.id.addfriends_btn_search);
		input = (EditText) findViewById(R.id.addfriends_input_text);
		input.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_URI);
		
		exist_list = new ArrayList<User>();
		arr_from_flist = new ArrayList<User>();
		arr_from_rlist = new ArrayList<User>(); 
		
		mSpinner = (Spinner) findViewById(R.id.addfriends_search_option);
		
		mSpinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, (String[])getResources().getStringArray(R.array.addfriends_spinner_list));
		mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);   
		mSpinner.setAdapter(mSpinnerAdapter); 
		
		
		before_intent = getIntent();
		myId = before_intent.getStringExtra("myId");
		exist_list = (ArrayList<User>) before_intent.getSerializableExtra("exist_list");
		f_img_factory = new HashMap<String, Bitmap>();
		
		FriendListTask f_task = new FriendListTask();
		f_task.execute(myId);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		btn_close.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		
		btn_search.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SearchResultTask r_task = new SearchResultTask();
				String opt = "";
				if (mSpinner.getSelectedItemPosition() == 0){
					opt = "id";
				}
				else{
					opt = "name";
				}
				r_task.execute(input.getText().toString(),opt);
			}
		});
		
		btn_invite.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				int flag = 0;
				arr_from_flist.clear();
				for(int i=0; i<list_chk.length; i++){
					if(list_chk[i] != null && list_chk[i].isChecked()){
						arr_from_flist.add(arr_user_f.get(i));
					}
				}
				if(arr_from_flist.isEmpty()){
					flag = 1;
				}
				else{
					if(!exist_list.isEmpty()){
						for(int i=0;  i<exist_list.size(); i++){
							for(int j=0; j<arr_from_flist.size(); j++){
								if(arr_from_flist.get(j).getId().equals(exist_list.get(i).getId())){
									flag = 2; //추가하려는 친구목록 중에 이미 팀원으로 존재하는 경우가 있는 경우 초대는 진행될 수 없다.
									break;
								}
							}
						}
					}
				}
				
				if(flag == 0){
					new AlertDialog.Builder(AddFriendsActivity.this).setTitle("Invite friends")
					.setIcon(R.drawable.members)
					.setMessage("Do you want to regist " + arr_from_flist.size() + " members?")
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int sumthin) {
							dialog.dismiss();
						}            
					})
					.setPositiveButton("Regist Member", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dlg, int arg2) {		        		 

							intent = new Intent();
							intent.putExtra("add_list",arr_from_flist);
							setResult(RESULT_OK, intent);
							finish();
						}
					}).show();
				}
				else if(flag == 1){
					Toast.makeText(AddFriendsActivity.this, "추가할 친구를 체크해 주세요.", Toast.LENGTH_SHORT).show();
				}
				else if(flag == 2){
					Toast.makeText(AddFriendsActivity.this, "추가할 친구가 이미 팀원으로 등록되어 있습니다.", Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		btn_delFriends.setOnClickListener(new OnClickListener() {

			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				arr_from_flist.clear();
				for(int i=0; i<list_chk.length; i++){
					if(list_chk[i].isChecked()){
						arr_from_flist.add(arr_user_f.get(i));
					}
				}
				DeletefriendTask df_task = new DeletefriendTask(AddFriendsActivity.this);
				df_task.execute();
			}
		});
		
		result_list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View v, int pos,
					long arg3) {
				// TODO Auto-generated method stub
				final int index = pos;
				//다이얼로그 띄우고 확인하면 arr_addlist에 추가
				new AlertDialog.Builder(AddFriendsActivity.this).setTitle(arr_user_r.get(index).getId())
				//.setIcon(arr_user_r.get(index).getPhoto())
				.setMessage("Do you want to regist member \n[" + arr_user_r.get(index).getName() + "]?")
				.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int sumthin) {
						dialog.dismiss();
					}            
				})
				.setNeutralButton("Add Friend", new DialogInterface.OnClickListener(){

					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						//서버에 친구추가 요청 후 친구목록 새로고침
						AddfriendTask ad_task = new AddfriendTask(AddFriendsActivity.this);
						User u = arr_user_r.get(index);
						ad_task.execute(u.getId());
						
					}

				})
				.setPositiveButton("Regist Member", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dlg, int sumthin) {		        		 
						arr_from_rlist.add(arr_user_r.get(index));

						//초대메시지 전송 메시지포맷 

						intent = new Intent();
						intent.putExtra("add_list",arr_from_rlist);
						setResult(RESULT_OK, intent);
						finish();
					}
				}).show();
			}
		});
	}

	class SearchResultTask extends AsyncTask<String, Void, Void>{
		HttpConnector conn;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			arr_user_r = new ArrayList<User>();
			uploadDialog = new ProgressDialog(AddFriendsActivity.this);
			uploadDialog.setTitle("Wait please...");
			uploadDialog.setMessage("Searching...");
			uploadDialog.setCancelable(false);
			uploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			uploadDialog.show();
			
			owner=true;
		}

		@Override
		protected Void doInBackground(String... params) {

			conn = new HttpConnector();
			Map<String, String> msgs = new HashMap<String,String>();

			msgs.put("id", params[0]);
			msgs.put("option", params[1]);


			try {
				String ret = conn.get("FindMember", msgs);
				JSONObject obj = new JSONObject(ret);
				JSONArray arr = obj.getJSONArray("members");
				int len = arr.length();

				for(int i=0; i<len; i++){
					JSONObject ob = arr.getJSONObject(i);

					String id = ob.getString("id"); 
					String name = ob.getString("name");
					String email = ob.getString("email");
					String photo = ob.getString("image");

					User ui = new User(id,name,email,photo);
					arr_user_r.add(ui);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			r_adapter = new ArrAdapter(AddFriendsActivity.this,arr_user_r,false);		
			result_list.setAdapter(r_adapter);
			
			uploadDialog.dismiss();
		}
	}

	class FriendListTask extends AsyncTask<String, Void, Void>{
		HttpConnector conn;
		
		

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			arr_user_f = new ArrayList<User>();
			uploadDialog = new ProgressDialog(AddFriendsActivity.this);
			uploadDialog.setTitle("Wait please...");
			uploadDialog.setMessage("Update friend list...");
			uploadDialog.setCancelable(false);
			uploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			
			uploadDialog.show();
			
			owner=true;
		}

		@Override
		protected Void doInBackground(String... params) {

			conn = new HttpConnector();
			Map<String, String> msgs = new HashMap<String,String>();

			msgs.put("id", params[0]);

			try {
				String ret = conn.get("Friend", msgs);
				JSONObject obj = new JSONObject(ret);
				JSONArray arr = obj.getJSONArray("members");
				int len = arr.length();

				for(int i=0; i<len; i++){
					JSONObject ob = arr.getJSONObject(i);

					String id = ob.getString("id"); 
					String name = ob.getString("name");
					String email = ob.getString("email");
					String photo = ob.getString("image");
					String logon = ob.getString("logon");

					User ui = new User(id,name,email,photo,logon);
					arr_user_f.add(ui);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			f_adapter = new ArrAdapter(AddFriendsActivity.this,arr_user_f,true);	
			friend_list.setAdapter(f_adapter);
			friend_list.setOnItemClickListener(mItemClickListener);
			uploadDialog.dismiss();
		}
	}
	
	class AddDelFriendsTask extends AsyncTask<String, Void, Boolean>{
		HttpConnector conn;

		@Override
		protected Boolean doInBackground(String... params) {

			conn = new HttpConnector();
			Map<String, String> msgs = new HashMap<String,String>();
			
			//Friend?action=명령&id=내아이디&Friend=친구아이디

			msgs.put("id", params[0]);
			msgs.put("action", params[1]);
			msgs.put("friend", params[2]);
			

			try {
				String ret = conn.get("Friend", msgs);
				JSONObject obj = new JSONObject(ret);
				String re_code = obj.getString("result");
				if(re_code.equals("ok")){
					return true;
				}
				else{
					return false;
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;
		}
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(result){
				Toast.makeText(getApplicationContext(), "Success!!", Toast.LENGTH_SHORT).show();
			}
			else{
				Toast.makeText(getApplicationContext(), "Duplicate friend id!!", Toast.LENGTH_SHORT).show();
			}
			
		}
	}
	
	class AddfriendTask extends AsyncTask<String, Void, Void>
	{
		HttpConnector conn;
		Context mCtx;
		
		
		public AddfriendTask(Context context)
		{
			mCtx = context;
		}
		@Override
		protected void onPreExecute() {
			conn = new HttpConnector();
			
			uploadDialog = new ProgressDialog(mCtx);
			uploadDialog.setTitle("Wait please...");
			uploadDialog.setMessage("Adding friends...");
			uploadDialog.setCancelable(false);
			uploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			
			uploadDialog.show();
			
			owner=true;
			
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			
			
			AddDelFriendsTask ad_task = new AddDelFriendsTask();
			ad_task.execute(myId,"add",params[0]);
			
			return null;			
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
			arr_user_f.clear();
			f_adapter = new ArrAdapter(AddFriendsActivity.this, arr_user_f, true);
			friend_list.setAdapter(f_adapter);
			
			uploadDialog.dismiss();
			
			FriendListTask f_task = new FriendListTask();
			f_task.execute(myId);		
		}
	}
	
	class DeletefriendTask extends AsyncTask<String, Void, Void>
	{
		HttpConnector conn;
		Context mCtx;
		
		
		public DeletefriendTask(Context context)
		{
			mCtx = context;
		}
		@Override
		protected void onPreExecute() {
			conn = new HttpConnector();
			
			uploadDialog = new ProgressDialog(mCtx);
			uploadDialog.setTitle("Wait please...");
			uploadDialog.setMessage("Deleting friends...");
			uploadDialog.setCancelable(false);
			uploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			
			uploadDialog.show();
			
			owner=true;
			
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... arg0) {
			for(int i=0; i<arr_from_flist.size(); i++){
				AddDelFriendsTask dl_task = new AddDelFriendsTask();
				dl_task.execute(myId,"delete",arr_from_flist.get(i).getId());
			}
			return null;			
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
			arr_user_f.clear();
			f_adapter = new ArrAdapter(AddFriendsActivity.this, arr_user_f, true);
			friend_list.setAdapter(f_adapter);
			
			uploadDialog.dismiss();
			
			FriendListTask f_task = new FriendListTask();
			f_task.execute(myId);			
		}
	}

	class ArrAdapter extends ArrayAdapter<User> {
		private ArrayList<User> items;
		private int rsrc;
		private String no_member = "";
		private boolean[] isCheckedConfrim;
		private boolean check = false;

		public ArrAdapter(Context ctx, ArrayList<User> data, boolean checkbox)
		{
			super(ctx,R.layout.row_friend_list, R.id.addfriends_row_id, data);
			this.items = data;
			this.rsrc = R.layout.row_friend_list;
			check = checkbox;
			if (check){
				isCheckedConfrim = new boolean[items.size()];
				list_chk = new CheckBox[items.size()];
			}
		}
		
		public void setChecked(int position) {
			isCheckedConfrim[position] = !isCheckedConfrim[position]; //check 여부를 받아서 해당 위치의 check 값을 바꿈
		}
		
		

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			View v = convertView;
			
			if (v == null) {
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(rsrc, null);
			} 
			User e = items.get(position);
			
			if (e != null) {
				TextView row_id = (TextView)v.findViewById(R.id.addfriends_row_id);
				TextView row_name = (TextView)v.findViewById(R.id.addfriends_row_name);
				ProgressBar row_pb = (ProgressBar)v.findViewById(R.id.addfriends_prog_bar);
				ImageView row_iv = (ImageView)v.findViewById(R.id.addfriends_row_photo);
				
				row_id.setText(e.getId());
				row_name.setText(e.getName());
				
				if(!f_img_factory.containsKey(e.getId())){
					row_iv.setVisibility(View.GONE);
					row_pb.setVisibility(View.VISIBLE);
					if (e.getPhoto() != null && !e.getPhoto().equals("null")){
						GetImageTask imgTask = new GetImageTask(row_iv,row_pb,e.getId(),f_img_factory);
						imgTask.execute(e.getId());
						
					}
					else{
						row_iv.setImageResource(R.drawable.anonymous);
						row_pb.setVisibility(View.GONE);
						row_iv.setVisibility(View.VISIBLE);
					}
				}
				else{
					row_iv.setImageBitmap(f_img_factory.get(e.getId()));
					row_pb.setVisibility(View.GONE);
					row_iv.setVisibility(View.VISIBLE);
				}
	        	
				CheckBox cb = (CheckBox)v.findViewById(R.id.addfriends_row_checkbox);
				cb.setTag(position);

				if (check == false){
					cb.setVisibility(View.GONE);					
				}
				else{
					//친구목록일 경우 체크박스 활성화 하고 
					cb.setVisibility(View.VISIBLE);
		            cb.setFocusable(false);
		            cb.setClickable(false);
		            cb.setChecked(isCheckedConfrim[position]);
		            list_chk[position]=cb;
		            
		            if(e.getLogon().equals("0")){
						row_id.setTextColor(Color.RED);
						row_name.setTextColor(Color.RED);
					}
				}
			}
			else{
				((TextView)v.findViewById(R.id.addfriends_row_id)).setText(no_member);
			}
			return v;
		}
	}
	
	private AdapterView.OnItemClickListener mItemClickListener = new 
			AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View arg1,
				int position, long arg3) {

			f_adapter.setChecked(position); //check 여부 확인해서 custom adapter에 바뀐값을 알림
			f_adapter.notifyDataSetChanged();

		}
	};
}